package com.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dao.IssueDao;
import com.dao.NotificationDao;
import com.dao.UserDao;
import com.entity.IssueEntity;
import com.entity.NotificationEntity;
import com.entity.UserEntity;
import com.model.Notification;

@Service
@Transactional
public class MailingService {

	@Autowired
	private MailUtil util;

	@Autowired
	private NotificationDao notificationDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private IssueDao issueDao;

	public void initializeSender(String host, String port) {
		Properties props = MailUtil.getProps();
		props.put("mail.smtp.host", host);// "smtp.gmail.com"
		props.put("mail.smtp.port", port);// 587
		MailUtil.setProps(props);
	}

	public void sendNotifications(String login, String password,
			List<Notification> notifications) {

		for (Notification notification : notifications) {
			List<NotificationEntity> multiNotification = new ArrayList<NotificationEntity>();
			NotificationEntity notificationEntity = new NotificationEntity();
			try {
				
				if (notification.isManyIssue()) {
					for (Integer id : notification.getIssuesId()) {
						notificationEntity = createNotification(notification, id);
						multiNotification.add(notificationEntity);
					}
				} else {
					multiNotification.add(createNotification(notification, notification.getIssueId()));
				}

				util.sendMail(notification.getMessage(), notification.getEmail(), login, password);
				for (NotificationEntity entity : multiNotification) {
					entity.setLastNotificationResult(true);
				}
			} catch (MessagingException e) {
				for (NotificationEntity entity : multiNotification) {
					entity.setLastNotificationResult(false);
				}
			}
			for (NotificationEntity entity : multiNotification) {
				notificationDao.saveOrUpdateNotificationEntity(entity);
			}
		}
	}

	private NotificationEntity createNotification(Notification notification, int issueId) {
		NotificationEntity notificationEntity = new NotificationEntity();
		UserEntity user = userDao.getUserByEmail(notification.getEmail());
		notificationEntity.setUser(user);
		notificationEntity.setIssue(issueDao.getById(IssueEntity.class, issueId));
		notificationEntity.setLastNotificationDate(new Date());
		return notificationEntity;
	}

}
